package com.pukea.app.medical.zyweixin;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class WxResponse {
	
	private boolean isSuccess = true;

	private String errCode = "";
	private String errMessage = "";
	
	private Object extReturnObject = null;

	
	public boolean isSuccess() {
		return isSuccess;
	}

	public void setSuccess(boolean isSuccess) {
		this.isSuccess = isSuccess;
	}

	public String getErrCode() {
		return errCode;
	}

	public void setErrCode(String errCode) {
		this.errCode = errCode;
	}

	public String getErrMessage() {
		return errMessage;
	}

	public void setErrMessage(String errMessage) {
		this.errMessage = errMessage;
	}

	public Object getExtReturnObject() {
		return extReturnObject;
	}

	public void setExtReturnObject(Object extReturn) {
		this.extReturnObject = extReturn;
	}
	
	public String toJson() {
		StringBuffer strJson = new StringBuffer("{\"errCode\":\"");
		strJson.append(isSuccess ? "200" : this.getErrCode()).append(
				"\",\"errMessage\":\"");
		strJson.append(this.getErrMessage()).append("\"");

		if (extReturnObject == null) {
			strJson.append("}");
		} else {
			if (extReturnObject instanceof Map) {
				strJson.append(",\"extReturn\":{");

				Map smsMap = (HashMap) extReturnObject;
				Iterator it = smsMap.entrySet().iterator();

				int i = 0;
				while (it.hasNext()) {
					Entry entry = (java.util.Map.Entry) it.next();

					if (i > 0) {
						strJson.append(",");
					}
					strJson.append("\"").append(entry.getKey()).append("\":");

					Object value = entry.getValue();
					if (value instanceof String) {
						strJson.append("\"")
								.append(nvl((String) entry.getValue()))
								.append("\"");
					} else if (value instanceof Double) {
						strJson.append((Double) entry.getValue());
					} else if (value instanceof Integer) {
						strJson.append((Integer) entry.getValue());
					}
					i++;
				}

				strJson.append("}");
			} else if (extReturnObject instanceof String) {

				strJson.append(",\"extReturn\":");

				strJson.append(extReturnObject);

			}
			strJson.append("}");
		}
		
		return strJson.toString();
	}
	
	private String nvl(String in){
		if(in==null) return "";
		
		return in;
	}
}
